package com.taomus.mytools.helper.other;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 导出ExcelExport
 * @author 穆仁超
 */
public class ExcelExportHelper {
	public static class Title{
		public Title(String name, Integer width) {
			super();
			this.name = name;
			this.width = width;
		}
		
		public Title(String name) {
			super();
			this.name = name;
		}
		
		public String name="";
		public Integer width=10;
	}
	private static String fileName = "";
	
	/**
	 * 获取导出的文件名
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getFileName(HttpServletRequest request) throws UnsupportedEncodingException{
		String browserName = request.getHeader("USER-AGENT");
		if (browserName.matches(".*MSIE.*")) {
			return URLEncoder.encode(fileName, "utf-8");
		} else {
			return  new String(fileName.getBytes("utf-8"),"ISO_8859_1");
		}
	}
	
	/**
	 * 导出Excel
	 * @param title
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static FileInputStream export(List<Title> title,List<List<String>> content) throws Exception{
		return export(title,content,null);
	}
	
	/**
	 * 导出Excel
	 * @param title
	 * @param content
	 * @param file_name
	 * @return
	 * @throws Exception
	 */
	public static FileInputStream export(List<Title> title,List<List<String>> content,String file_name) throws Exception{
		String realPath = System.getProperty("user.dir");
		if(file_name == null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			fileName = sdf.format(new Date())+".xls";
		}else{
			fileName = file_name;
		}
		File file = new File(realPath + "//downloads//");//导出文件存放的位置
		if (!file.exists()) {
			file.mkdirs();
		}
		realPath = realPath + "//downloads//" + fileName;
		//创建工作薄
		WritableWorkbook workbook = Workbook.createWorkbook(new File(realPath));
		//创建新的一页
		WritableSheet sheet = workbook.createSheet("First Sheet", 0);
		
		WritableCellFormat cf = new WritableCellFormat();
		cf.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
		
		for(int i=0;i<title.size();i++){
			//创建要显示的具体内容
			Label label = new Label(i,0,title.get(i).name, cf);
			sheet.setColumnView(i, title.get(i).width);
			sheet.addCell(label);
		}
		if(content != null){
			for(int j=0;j<content.size();j++){
				List<String> ct = content.get(j);
				for(int k = 0;k<ct.size();k++){
					Label example = new Label(k,j+1,ct.get(k), cf);
					sheet.addCell(example);
				}
			}
		}
		
		workbook.write();
		workbook.close();
		return  new FileInputStream(new File(realPath));
	}
}
